Page({
  data: {
    jobs: [],
    currentUsername: '', // 当前用户名
    resumes: [], // 简历数据
    showResumePicker: false, // 控制简历选择器的显示与隐藏
    selectedJob: null, // 选中的岗位信息
    selectedResume: null, // 选中的简历信息
  },

  onLoad: function () {
    // 获取当前用户名
    const username = wx.getStorageSync('username');
    this.setData({
      currentUsername: username
    });
    this.loadJobs(); // 加载岗位数据
  },

  // 获取岗位数据
  loadJobs() {
    wx.showLoading({ title: '加载中' });
    wx.request({
      url: 'http://192.168.172.134:5000/api/getPositionByUsername',
      method: 'GET',
      data: {
        currentUsername: this.data.currentUsername // 传递当前用户名
      },
      success: (res) => {
        if (res.data.code === 200) {
          this.setData({ jobs: res.data.data });
        } else {
          wx.showToast({
            title: '加载岗位数据失败',
            icon: 'none'
          });
        }
      },
      complete: () => wx.hideLoading()
    });
  },

  //获取简历数据
  loadResumes() {
    wx.showLoading({ title: '加载中' });
    wx.request({
      url: 'http://192.168.172.134:5000/api/resumes',
      method: 'GET',
      data: {
        student_id: this.data.currentUsername // 传递当前用户名
      },
      success: (res) => {
        if (res.data.code === 200) {
          this.setData({ resumes: res.data.data });
        } else {
          wx.showToast({
            title: '加载简历数据失败',
            icon: 'none'
          });
        }
      },
      complete: () => wx.hideLoading()
    });
  },

  // 一键投递简历
  submitResume(e) {
    this.loadResumes(); // 加载简历数据
    const { id, email } = e.currentTarget.dataset;
    const job = this.data.jobs.find(j => j.id == id);

    if (!email) {
      wx.showToast({ title: '该岗位暂无邮箱', icon: 'none' });
      return;
    }

    this.setData({
      showResumePicker: true,
      selectedJob: { id, email, ...job }
    });
  },

  // 选择简历/ 选择简历
  selectResume(e) {
    const { index } = e.currentTarget.dataset;
    const selectedResume = this.data.resumes[index];
    this.sendResume(selectedResume);
    this.closePicker();
  },

  onResumeChange(e) {
    const { value } = e.detail;
    this.setData({ selectResumeIndex: value });
  },

  // 关闭弹窗
  closePicker() {
    this.setData({ showResumePicker: false });
  },

  sendResume(resume){
    wx.showLoading({ title: '发送中...' });
    try{
      const res= wx.request({
        url: 'http://192.168.172.134:5000/api/sendEmail',
        method: 'POST',
        header: {
          'Content-Type': 'application/x-www-form-urlencoded' // 明确设置Content-Type
        },
        data: {
          email: this.data.selectedJob.email,
          resume_id: resume.id,
        },
      });
      if (res.data.code === 200) {
        wx.showToast({ title: '简历投递成功', icon: 'success' });
      } else {
        wx.showToast({ title: '简历投递失败', icon: 'none' });
      }
    }catch (error) {
      wx.showToast({ title: '简历投递成功', icon: 'success' });
    }finally{
      wx.hideLoading();
    }
  },

});